package com.sina.mysql.utils;

import org.hibernate.boot.MetadataBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ClassUtils;

import java.io.IOException;

/**
 * @ClassName ConfigHelper
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:49
 * @Version 1.0
 */
public abstract class ConfigHelper {

    private static final Logger LOG = LoggerFactory.getLogger( ConfigHelper.class );

    @SuppressWarnings("unchecked")
    public static void configMetadataSources(ResourceLoader resourceLoader, MetadataBuilder metadataBuilder) throws IOException, ClassNotFoundException {

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( resourceLoader );

        Resource[] resources = resolver.getResources( "classpath*:com/sina/domain/**/*.class" );
        String classFilePath, filePath, className;
        Class<?> clazz;
        int index;

        for (Resource resource : resources) {

            filePath = resource.getURI().toString();
            LOG.trace( "classFilePath:{}", filePath );
            index = filePath.indexOf( "com/sina/domain" );
            classFilePath = filePath.substring( index );

            className = ClassUtils.convertResourcePathToClassName( classFilePath );
            className = className.substring( 0, className.length() - ".class".length() );
            clazz = ClassUtils.forName( className, resourceLoader.getClassLoader() );

            if (clazz.isEnum() && CodeEnum.class.isAssignableFrom( clazz )) {
                LOG.debug( "className:{}", className );
                CodeEnumType type = CodeEnumType.getInstance( (Class<? extends Enum<?>>) clazz );
                metadataBuilder.applyBasicType( type, clazz.getName() );

            }

        }

    }
}

